#include<iostream>
#include<queue>
#include<vector>
using namespace std;

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        int m = maze.size(), n = maze[0].size();

        bool vis[101][101];
        memset(vis, 0, sizeof(vis));
        queue<pair<int, int>> q;

        q.push({ entrance[0],entrance[1] });
        vis[entrance[0]][entrance[1]] = true;

        int step = 0;
        while (q.size())
        {
            step++;
            int sz = q.size();
            for (int i = 0; i < sz; i++)
            {
                int a = q.front().first;
                int b = q.front().second;
                q.pop();

                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && maze[x][y] == '.')
                    {
                        if (x == 0 || x == m - 1 || y == 0 || y == n - 1) return step;
                        q.push({ x,y });
                        vis[x][y] = true;
                    }

                }
            }
        }

        return -1;
    }
};